package com.sxt.a01;

import javax.swing.*;
import java.awt.*;

/**
 * @author songjun
 */
public class BallGame extends JFrame {

    Image ball = Toolkit.getDefaultToolkit().getImage("images/ball.png");
    Image desk = Toolkit.getDefaultToolkit().getImage("images/desk.jpg");

    double x = 100;//小球x坐标
    double y = 100;//小球y坐标
    double degree = 3.14 / 3;//角度

    /**
     * 画窗口
     *
     * @param g
     */
    @Override
    public void paint(Graphics g) {
        System.out.println("窗口被画了一次！");
        g.drawImage(desk, 0, 0, null);
        g.drawImage(ball, (int) x, (int) y, null);

        x = x + 10 * Math.cos(degree);//10是速度
        y = y + 10 * Math.sin(degree);

        //碰到上下边界
        if (y > 500 - 40 - 30 || y < 40 + 40) {
            degree = -degree;
        }
        //碰到左右边界
        if (x < 40 || x > 856 - 40 - 30) {
            degree = 3.14 - degree;
        }
    }

    /**
     * 加载窗口
     */
    public void launchFrame() {
        setSize(856, 500);
        setLocation(50, 50);
        setTitle("桌球小游戏");
        setVisible(true);
        while (true) {
            repaint();
            try {
                Thread.sleep(40);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        BallGame ballGame = new BallGame();
        ballGame.launchFrame();
    }
}
